package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Doc;
import com.jiawa.wiki.domain.DocExample;
import com.jiawa.wiki.mapper.DocMapper;
import com.jiawa.wiki.req.DocQueryReq;
import com.jiawa.wiki.req.DocSaveReq;
import com.jiawa.wiki.resp.DocQueryResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DocService {

    @Resource
    public DocMapper docMapper;

    @Resource
    public SnowFlake snowFlake;

    private final static Logger LOG = LoggerFactory.getLogger(DocService.class);

    public PageResp<DocQueryResp> getlist(DocQueryReq req) {
        //ctrl+alt+v
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();


        PageHelper.startPage(req.getPage(), req.getSize());
        //直接从数据库中取出的数据
        List<Doc> docList = docMapper.selectByExample(docExample);

        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        //ctrl+alt+v、
        //PageResp 类
        //pageResp 对象
        PageResp<DocQueryResp> pageResp = new PageResp<>();

        pageResp.setTotal(pageInfo.getTotal());

        pageResp.setList(list);

        return pageResp;

    }

    /*
     * @Description:一次性查出所有书
     * @param null
     * @return: null
     * @Author: wengyiting
     * @Date: 2024/5/31 下午 3:09
     */

    public List<DocQueryResp> all() {
        //ctrl+alt+v
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");

        //直接从数据库中取出的数据
        List<Doc> docList = docMapper.selectByExample(docExample);

        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        return list;

    }


    //编辑
    public void save(DocSaveReq req) {

        Doc doc = CopyUtil.copy(req, Doc.class);

        if (!ObjectUtils.isEmpty(req.getId())) {
            //更新
            docMapper.updateByPrimaryKey(doc);
        } else {
            //新增
            doc.setId(snowFlake.nextId());
            docMapper.insert(doc);
        }
    }

    //删除
    public void delete(long id){
        docMapper.deleteByPrimaryKey(id);
    }


}